//
//  HomeController.swift
//  SwiftWB
//
//  Created by 远成物流 on 2017/6/22.
//
//

import UIKit
import MJRefresh

class HomeController: BaseViewController {
    
    lazy var titleBtn : TitleButton = TitleButton()
    lazy var popoverAnimator : PopoverAnimator = PopoverAnimator { [weak self](presented) in
        self!.titleBtn.isSelected = presented
    }
    lazy var viewModels : [StatusViewModel] = [StatusViewModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        vistorView.addAnimation()
        if !isLogin{
            return
        }
        
        setupNavigator()
        
        setupHeader()
        setupFooter()
    }
}

///Mark - UI
extension HomeController{
    ///设置导航栏
    func setupNavigator() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName:"navigationbar_pop")
        
        titleBtn.setTitle(UserAccoutViewModel.shareInstance.account?.screen_name ?? "微博", for: .normal)
        titleBtn.addTarget(self, action: #selector(titleBtnAction), for: .touchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    //设置下拉刷新
    func setupHeader() {
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNewStatus))
        header?.setTitle("下拉刷新", for: .idle)
        header?.setTitle("释放更新", for: .pulling)
        header?.setTitle("加载中...", for: .refreshing)
        
        tableView.mj_header = header
        
        tableView.mj_header.beginRefreshing()
    }
    
    //设置上拉加载
    func setupFooter() {
        tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreStatus))
    }
}

///Mark - 点击事件监听
extension HomeController{
    @objc fileprivate func titleBtnAction(button:TitleButton) {
        button.isSelected = !button.isSelected
        
        let popover = PopoverController()
        popover.modalPresentationStyle = .custom
        popover.transitioningDelegate = popoverAnimator
        popoverAnimator.presentedFrame = CGRect(x: (view.frame.size.width - 100)*0.5, y: 55, width: 100, height: 250)
        
        present(popover, animated: true, completion: nil)
    }
}

/// Mark - Net request
extension HomeController{
    
    @objc fileprivate func loadNewStatus(){
        loadStatues(true)
    }
    
    @objc fileprivate func loadMoreStatus(){
        loadStatues(false)
    }
    
    fileprivate func loadStatues(_ isNewData:Bool) {
        var since_id = 0
        var max_id = 0
        
        if isNewData {
            since_id = viewModels.first?.status?.mid ?? 0
        }else{
            max_id = viewModels.first?.status?.mid ?? 0
            max_id = max_id == 0 ? 0 : (max_id-1)
        }
        
        NetworkHelper.shareInstance.loadStatues(sinceId: since_id, maxId: max_id) { (result:[[String : AnyObject]]?, error:Error?) in
            
            if error != nil {
                return
            }
            
            guard let resultArray = result else{
                return
            }
            
            //遍历数组，将字典转模型
            var tempArray = [StatusViewModel]()
            for statusDict in resultArray{
                let status = Status(dict: statusDict)
                let viewModel = StatusViewModel(status: status)
                tempArray.append(viewModel)
            }
            
            //将数据添加到模型数组中
            if isNewData {
                self.viewModels = tempArray + self.viewModels
            }else{
                self.viewModels = self.viewModels + tempArray
            }
            
            //缓存图片
            self.cacheImage(tempArray)
        }
    }
    
    private func cacheImage(_ viewModels : [StatusViewModel]){
        
    }
}

